axios.defaults.baseURL = 'http://ajax-base-api-t.itheima.net'

//获取元素
const tb = document.querySelector('#tb')
// 添加列表
const goodlists = async () => {
  const { data: res } = await axios.get('/api/getbooks')
  const { data } = res
  console.log(res)
  const html = data
    .map((item) => {
      return `<tr>
         <td>${item.id}</td>
         <td>${item.bookname}</td>
         <td>${item.author}</td>
         <td>${item.publisher}</td>
         <td><a href="#" data-id="${item.id}">删除</a></td>
       </tr>`
    })
    .join('')
  tb.innerHTML = html
}

goodlists()
// 添加图书
// 获取元素
const form = document.querySelector('#bookForm')
form.addEventListener('submit', async function (e) {
  e.preventDefault()
  const data = serialize(form, { hash: true })
  console.log(data)
  const { data: res } = await axios.post('/api/addbook', data)
  alert(res.msg)
  if (res.status !== 201) return
  form.reset()
  goodlists()
})
// 删除图书
tb.addEventListener('click', async function (e) {
  if (e.target.tagName === 'A') {
    let id = e.target.dataset.id
    const { data: res } = await axios.get('/api/delbook?id=' + id)
    console.log(res)
    alert('删除成功')
    goodlists()
  }
})
// 筛选
const btn = document.querySelector('#btnAnd')
btn.addEventListener('click', async function () {
  const data = serialize(form, { hash: true })
  const bookname = data.bookname
  const author = data.author
  const publisher = data.publisher
  const { data: res } = await axios({
    url: '/api/getbooks',
    method: 'GET',
    params: {
      bookname,
      author,
      publisher,
    },
  })
  //  const { data } = res
  console.log(res)
  const html = res.data
    .map((item) => {
      return `<tr>
     <td>${item.id}</td>
     <td>${item.bookname}</td>
     <td>${item.author}</td>
     <td>${item.publisher}</td>
     <td><a href="#" data-id="${item.id}">删除</a></td>
   </tr>`
    })
    .join('')
  tb.innerHTML = html
})
